<?php

namespace app\api\controller;

use app\admin\model\cms\Channels;
use app\admin\model\User as UserModel;
use app\admin\model\rotation\chart\Management;
use app\admin\model\UserGroup;
use app\admin\model\UserRule;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\UserLike;
use app\common\model\UserForward;
use app\common\model\UserFavorite;
use app\common\model\UserView;
use app\common\model\Comment;
use app\admin\model\cms\Platepost;
use fast\Random;
use think\Cache;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getCaptca', 'get_management', 'getcolumninfo','logout'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');

        $wechat_code = $this->request->param('code','');//微信小程序code 用来换openid
        $wechat_openid = '';//微信小程序openid
        if ($wechat_code){
            $getWechatOpenid = $this->getWechatOpenid($wechat_code);
            if ($getWechatOpenid['code'] == 500){
                $this->error($getWechatOpenid['msg']);
            }
            $wechat_openid = $getWechatOpenid['data']['openid'];
        }

        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if (Cache::get('captcha_' . $this->request->post('token')) != strtoupper($this->request->post('captcha'))) {
            $this->error(__('Captcha is incorrect'));
        } else {
            Cache::rm('captcha_' . $this->request->post('token'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $data['userinfo']['like'] = UserLike::where('user_id', $this->auth->id)->count();
            $data['userinfo']['favorite'] = UserFavorite::where('user_id', $this->auth->id)->count();
            $data['userinfo']['view'] =  UserView::where('user_id', $this->auth->id)->count();
            $data['userinfo']['forward'] = UserForward::where('user_id', $this->auth->id)->count();
            $data['userinfo']['comment'] = Comment::where('user_id', $this->auth->id)->count();
            $data['userinfo']['post'] = Platepost::where('user_id', $this->auth->id)->count();

            if($wechat_openid){
                $this->updateUserWechatOpenid($this->auth->id,$wechat_openid);//更新用户微信openid
            }

            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');//手机号
        $captcha = $this->request->post('captcha');//验证码

        $wechat_code = $this->request->param('code','');//微信小程序code 用来换openid
        $wechat_openid = '';//微信小程序openid
        if (!empty($wechat_code)){
            $getWechatOpenid = $this->getWechatOpenid($wechat_code);
            if ($getWechatOpenid['code'] == 500){
                $this->error($getWechatOpenid['msg']);
            }
            $wechat_openid = $getWechatOpenid['data']['openid'];
        }


        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\admin\model\User::where('mobile',$mobile)->find();
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
            $is_exist_user = 1;//账号已存在就是1
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            $is_exist_user = 0;//账号新注册就是0
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = [
                'userinfo' => $this->auth->getUserinfo(),
                'is_exist_user' => $is_exist_user,
                'is_required_userinfo'=>\app\common\model\Config::where('name','is_required_userinfo')->value('value') ?? 0,//新注册用户时是否需要填写详细信息|0:否,1:是
            ];

            if($wechat_openid){
                $this->updateUserWechatOpenid($data['userinfo']['id'],$wechat_openid);//更新用户微信openid
            }

            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname') ?? generateRandomName();//昵称
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $token = $this->request->post('token');
        $invitation_code = $this->request->post('invitation_code') ?? '';//6位邀请码|默认为空
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (Cache::get('captcha_' . $token) != strtoupper($code)) {
            $this->error(__('Captcha is incorrect'));
        } else {
            Cache::rm('captcha_' . $token);
        }
//        $ret = Sms::check($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }
        $ret = $this->auth->register($username, $password, $email, $mobile, ['invitation_code'=>$invitation_code,'nickname'=>$nickname]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success('修改成功');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success('修改成功');
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //获取栏目列表
    public function getcolumnlist()
    {
        $user = $this->auth->getUser();//用户信息
        $column = Channels::where('status', 'in', [1, 2, 3])
            ->where('parent_id', 0)
            ->order('list_order', 'desc')
            ->select();
        $column_rule_model = new UserModel();
        $column_rule = $column_rule_model->getUserChannels($user);
        foreach ($column as $key => $value) {
            if ($value['status'] == 1 || in_array($value['id'], $column_rule)) {
                $column[$key]['authorize'] = true;
            } else {
                $column[$key]['authorize'] = false;
            }
        }
        $this->success('获取成功', $column);
    }

    //栏目详情
    public function getcolumninfo()
    {
        $column = Channels::find($this->request->get("column_id"));
        $column['child'] = Channels::where('parent_id', $column['id'])->select();
        $this->success('获取成功', $column);
    }

    public function getCaptca()
    {
        $s = new \ClientCaptcha();
        $res = $s->entry();
        $token = md5(uniqid());
        Cache::set('captcha_' . $token, $res['code'], 300);
        $this->success('获取成功', ['token' => $token, 'img' => 'data:image/jpeg;base64,' . base64_encode($res['content'])]);
    }

    //轮播图列表
    public function get_management()
    {
        $data = Management::where('statusswitch', 1)->order('sort', 'desc')->select();
        $res = $data;
        foreach($res as &$v){
            if ($v['smallimage']) {
                if (substr($v['smallimage'], 0, 1) === '/') {
                    $v['smallimage'] = obsurl($v['smallimage']);
                }
            }


            $v['channels_id_1'] = '';//顶级分类id
            $v['channels_id_2'] = '';//二级分类id
            $v['channels_name_1'] = '';//顶级分类名称
            $v['channels_name_2'] = '';//二级分类名称

            if ($v['type'] == 2){
                $channels = Channels::where('id',$v['channels_id'])->find();
                if ($channels['parent_id']){
                    //二级
                    $channels_top = Channels::where('id',$channels['parent_id'])->find();//查顶级
                    if ($channels_top){
                        $v['channels_name_2'] = $channels['name'];//分类名称
                        $v['channels_id_2'] = $channels['id'];//分类名称

                        $v['channels_id_1'] = $channels_top['id'];//顶级分类id
                        $v['channels_name_1'] = $channels_top['name'];//顶级分类名称
                    }
                }else{
                    $v['channels_id_1'] = $channels['id'];//顶级分类id
                    $v['channels_name_1'] = $channels['name'];//顶级分类名称
                }
            }

        }
        $this->success('获取成功', $res);
    }

    //上传用户名片
    public function upload_user_images()
    {
        $file = $this->request->file('file');
        $user = $this->auth->getUser();
        $info = $file->validate(['size' => 1024 * 1024 * 2, 'ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'user');
        if ($info) {
            $file_path = '/uploads/user/' . $info->getSaveName();
            $user->where(['id' => $user->id])->update(['group_id' => 2, 'user_image' => $file_path, 'user_image_upload_time' => time(), 'member_type' => 'TrialMember', 'member_make_time' => time()]);//member_type|tourist是游客、TrialMember试用会员，member正式会员
            $this->success('上传成功', ['url' => $file_path]);
        } else {
            $this->error($file->getError());
        }
    }

    /**
     * 获取微信小程序openid
     * @param $code获取微信小程序openid
     */
    private function getWechatOpenid($code)
    {
        if (!$code) {
            $this->error('缺少参数');
        }
        $appid = \app\common\model\Config::where('group', 'we_chat_pay')->where('name', 'miniapp_id')->value('value'); //小程序的app_id

        $secret = \app\common\model\Config::where('group', 'we_chat_pay')->where('name', 'miniapp_secret')->value('value'); //小程序的secret

        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $get_token_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        $json_obj = json_decode($res, true);
        //dd($json_obj);
        // print_r($json_obj);
        // $openid = $json_obj['openid'] ?? null;
        $res = [
            'code'=>200,
            'msg'=>'success',
        ];
        if ($json_obj['errmsg'] ?? false){
            $res = [
                'code'=>500,
                'msg'=>$json_obj['errmsg'],
            ];
        }else{
            $res = [
                'code'=>200,
                'msg'=>'success',
                'data'=>$json_obj
            ];
        }
        return $res;
    }

    //更新用户微信openid
    private function updateUserWechatOpenid($user_id,$wechat_openid){
        if (!$wechat_openid) {
            $this->error('缺少wechat_openid');
        }
        $user = $this->auth->getUser();//用户信息
        \app\admin\model\User::where('id',$user_id)->update([
            'wechat_openid'=> $wechat_openid
        ]);
        return true;
    }
}
